package com.rain.shoppingscienceproj.ui.activity.shopping;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.rain.shoppingscienceproj.R;
import com.rain.shoppingscienceproj.http.BaseSubscriber;
import com.rain.shoppingscienceproj.http.ExceptionHandle;
import com.rain.shoppingscienceproj.http.RetrofitClient;
import com.rain.shoppingscienceproj.module.Goods;
import com.rain.shoppingscienceproj.ui.activity.BaseActivity;
import com.rain.shoppingscienceproj.ui.activity.search.SearchLocalityActivity;
import com.rain.shoppingscienceproj.ui.adapter.GoodsAdapter;
import com.rain.shoppingscienceproj.ui.utile.TitleUtils;
import com.rain.shoppingscienceproj.utils.AppManager;
import com.rain.shoppingscienceproj.utils.LoadingDialog;
import com.rain.shoppingscienceproj.utils.toast.ToastUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class GoodsListActivity extends BaseActivity {


    @BindView(R.id.rv_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.message_iv)
    ImageView message_iv;

    @BindView(R.id.ll_no_data)
    LinearLayout ll_no_data;

    private GoodsAdapter goodsAdapter;

    String provinceId, typeId;

    private int type = 1;
    private int lastOffset;//距离

    private int lastPosition;//第几个item

    private String desc = "goods_num";

    private int page = 1;

    private List<Goods> goodsList = new ArrayList<>();

    @OnClick(R.id.ll_volume)
    void volume() {
        desc = "goods_num";
        initData(2);
    }

    @OnClick(R.id.ll_new_goods)
    void newGoods() {
        desc = "ctime";
        initData(2);
    }

    /**
     * 切换布局
     */
    @OnClick(R.id.iv_switchover)
    void switchover() {
        if (type == 1) {
            type = 2;
            mRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));
            goodsAdapter = new GoodsAdapter(this, type);
        } else {
            type = 1;
            mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
            goodsAdapter = new GoodsAdapter(this, type);
        }
        mRecyclerView.setAdapter(goodsAdapter);
        if (mRecyclerView.getLayoutManager() != null && lastPosition >= 0) {
            ((LinearLayoutManager) mRecyclerView.getLayoutManager()).scrollToPositionWithOffset(lastPosition, lastOffset);
        }
        goodsAdapter.setItemClickListener(shopId -> {
            startActivitys(ShoppingDetailsActivity.class, shopId);
        });
        initData(2);
    }

    /**
     * 搜索
     */
    @OnClick(R.id.et_finding_search)
    void search() {
        Intent intent = new Intent(GoodsListActivity.this, SearchLocalityActivity.class);
        intent.putExtra("type", 3);
        intent.putExtra("provinceId", provinceId);
        intent.putExtra("typeId", typeId);
        startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_list);
        AppManager.getAppManager().addActivity(this);
        ButterKnife.bind(this);
        TitleUtils.TitleView(this, "商品列表");
        provinceId = getIntent().getStringExtra("type");
        typeId = getIntent().getStringExtra("id");
        loadingDialog = new LoadingDialog(this, "正在加载...");
        initView();
//        initData(1);
        initListener();
    }

    private void initView() {
        message_iv.setVisibility(View.GONE);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        goodsAdapter = new GoodsAdapter(this, type);
        mRecyclerView.setAdapter(goodsAdapter);
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadmore(true);

    }

    @Override
    public void onStart() {
        super.onStart();
        refresh();
    }

    private void initData(int i) {
        Map<String, String> map = new HashMap<>();
        map.put("provinceId", provinceId);
        map.put("classId", typeId);
        map.put("page", page + "");
        map.put("orderBy", desc);
        loadingDialog.show();
        RetrofitClient.getInstance(this)
                .createBaseApi()
                .typeGoods(map, new BaseSubscriber<List<Goods>>(this) {
                    @Override
                    public void onError(ExceptionHandle.ResponeThrowable e) {
                        ToastUtils.showShortToast(e.Message);
                        loadingDialog.dismiss();
                        ll_no_data.setVisibility(View.VISIBLE);
                        refreshLayout.setVisibility(View.GONE);
                    }

                    @Override
                    public void onNext(List<Goods> goods) {
                        super.onNext(goods);
                        if (page == 1) {
                            if (goods.size() == 0) {
                                ll_no_data.setVisibility(View.VISIBLE);
                                refreshLayout.setVisibility(View.GONE);
                            } else {
                                ll_no_data.setVisibility(View.GONE);
                                refreshLayout.setVisibility(View.VISIBLE);
                            }
                        } else {
                            if (goods.size() == 0) {
                                ToastUtils.showShortToast("没有更多数据了...");
                            }
                            ll_no_data.setVisibility(View.GONE);
                            refreshLayout.setVisibility(View.VISIBLE);
                        }
                        finishLoad();
                        loadingDialog.dismiss();
                        if (i == 1) {
                            goodsList.addAll(goods);
                        }
                        goodsAdapter.setList(goodsList);
                    }
                });
    }

    private void initListener() {
        refreshLayout.setOnRefreshListener(refreshlayout -> refresh());
        refreshLayout.setOnLoadmoreListener(refreshlayout -> load());
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (recyclerView.getLayoutManager() != null) {
                    View childAt = recyclerView.getLayoutManager().getChildAt(0);
                    lastOffset = childAt.getTop();
                    lastPosition = recyclerView.getLayoutManager().getPosition(childAt);
                }
            }
        });
        goodsAdapter.setItemClickListener(shopId -> {
            startActivitys(ShoppingDetailsActivity.class, shopId);
        });
    }

    public void finishLoad() {
        refreshLayout.finishLoadmore();
        refreshLayout.finishRefresh();
    }

    private void refresh() {
        page = 1;
        goodsList = new ArrayList<>();
        initData(1);
        refreshLayout.finishRefresh();
    }

    private void load() {
        page++;
        initData(1);
        refreshLayout.finishLoadmore();
    }

}
